﻿
using System.Collections.Generic;
using System.Linq;

namespace FlashPay.DAO.Impl.Sys
{
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity;
    using FlashPay.Entity.Response.Sys;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.DAO.Sys;
    using FlashPay.Entity.Enum;
    using System;
    using Microsoft.EntityFrameworkCore;
    using System.Data;
    using System.Data.Common;
    using MySql.Data.MySqlClient;
    using FlashPay.Entity.Request.Sys;
    using System.Linq.Expressions;

    /// <summary>
    /// 參數管理DAO
    /// </summary>
    public class SysConfigDAOImpl : SysConfigDao, IDisposable
    {
        #region 注入
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public SysConfigDAOImpl(FlashPayContext context)
        {
            _context = context;
        }
        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取系统配置
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>菜单</returns>
        public SysConfig Get(int configId)
        {
            return _context.SysConfig.Where(x => x.ConfigId == configId).FirstOrDefault();
        }

        /// <summary>
        /// 获取系统配置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<SysConfig> GetList(SysConfigQuery query)
        {
            var where = PredicateBuilder.True<SysConfig>();
            if (query.TypeIds != null && query.TypeIds.Any())
            {
                where = where.And(e => query.TypeIds.Contains(e.ConfigValue));
            }
            if (!string.IsNullOrEmpty(query.ConfigCode))
            {
                where = where.And(e => e.ConfigCode == query.ConfigCode);
            }

            where = where.And(e => e.CompanyId == (int)ReceiptTrans.TranCompanyId);

            var list = _context.SysConfig.Where(where.Compile()).ToList();
            return list;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        public int Add(SysConfig model, FlashPayContext flashPayContext = null)
        {
            _context.SysConfig.Add(model);
            _context.SaveChanges();
            return model.ConfigId;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        public bool Update(SysConfig model, FlashPayContext flashPayContext = null)
        {
            bool result = false;
            var sysConfig = _context.SysConfig.Find(model.ConfigId);
            if (sysConfig != null)
            {
                sysConfig.ConfigCode = model.ConfigCode;
                sysConfig.ConfigValue = model.ConfigValue;
                sysConfig.ConfigContent = model.ConfigContent;
                sysConfig.CompanyId = model.CompanyId;
                sysConfig.Description = model.Description;

                _context.Entry<SysConfig>(sysConfig);
                _context.SaveChanges();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="configId">系统编号</param>
        public bool Delete(int configId)
        {
            var model = _context.SysConfig.Find(configId);
            if (model != null)
            {
                _context.SysConfig.Remove(model);
                if (_context.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<SysConfig></returns>
        public PagedList<SysConfigResponse> GetPager(SysConfigQuery query)
        {
            var q = from sc in _context.SysConfig
                    join c in _context.Company on sc.CompanyId equals c.CompanyId
                    select new SysConfigResponse
                    {
                        ConfigId = sc.ConfigId,
                        CompanyId = sc.CompanyId,
                        CompanyName = c.CompanyName,
                        ConfigCode = sc.ConfigCode,
                        ConfigContent = sc.ConfigContent,
                        ConfigValue = sc.ConfigValue,
                        Description = sc.Description
                    };
            //分类代码
            if (!string.IsNullOrEmpty(query.ConfigCode))
            {
                q = q.Where(c => c.ConfigCode.Contains(query.ConfigCode));
            }
            //分类名称
            if (!string.IsNullOrEmpty(query.ConfigContent))
            {
                q = q.Where(c => c.ConfigContent.Contains(query.ConfigContent));
            }
            //公司名称
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                q = q.Where(c => c.CompanyName.Contains(query.CompanyName));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            if (query.CompanyId > 0)
            {
                q = q.Where(c => c.CompanyId.Equals(query.CompanyId));
            }

            int currentPage = query.CurrentPageIndex.Value;
            int pageSize = query.PageSize.Value;

            var row = q.OrderByDescending(r => r.ConfigCode).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            var count = q.Count();

            return new PagedList<SysConfigResponse>
            {
                TData = row,
                CurrentPageIndex = currentPage,
                TotalCount = count,
                Success = true
            };
        }

        #region 第三方接口相关
        /// <summary>
        /// 获取第三方接口列表
        /// </summary>
        public PagedList<PaymentInterfaceNew> GetPayMentInterfaceList(PaymentInterfaceQuery query)
        {
            var q = from s in _context.PaymentInterface
                    join c in _context.Company on s.CompanyID equals c.CompanyId
                    select new PaymentInterfaceNew
                    {
                        PaymentInterfaceID = s.PaymentInterfaceID,
                        CompanyID = s.CompanyID,
                        SortNo = s.SortNo,
                        PaymentType = s.PaymentType,
                        CompanyName = s.CompanyName,
                        SecretKey = s.SecretKey,
                        PaymentStart = s.PaymentStart.ToString("#0.00"),
                        PaymentEnd = s.PaymentEnd.ToString("#0.00"),
                        WithdrawalBank = s.WithdrawalBank,
                        DepositType = s.DepositType,
                        PaymentMax = s.PaymentMax,
                        LimitOpenDate = s.LimitOpenDate.Value == null ? "00:00" : Convert.ToDateTime(s.LimitOpenDate).ToString("HH:mm"),
                        LimitCloseDate = s.LimitCloseDate.Value == null ? "00:00" : Convert.ToDateTime(s.LimitCloseDate).ToString("HH:mm"),
                        LimitRepeat = s.LimitRepeat,
                        LimitStatus = s.LimitStatus,
                        EnableBalanceCheck = s.EnableBalanceCheck,
                        Balance = s.Balance.ToString("#0.00"),
                        BalancePermission = query.permission.BalanceView? "PaymentInterface0006":"",
                        Company = c
                    };

            var yy = q.ToList();

            #region 搜索条件
            //公司名称
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                q = q.Where(c => c.Company.CompanyName.Contains(query.CompanyName));
            }
            //公司名称
            if (query.PaymentType.HasValue)
            {
                q = q.Where(c => c.PaymentType == query.PaymentType.Value);
            }
            //接口公司名称
            if (!string.IsNullOrEmpty(query.InterfaceCompanyName))
            {
                q = q.Where(c => c.CompanyName.Contains(query.InterfaceCompanyName));
            }

            int delStatus = (int)PaymentInterfaceStatus.删除;

            //状态
            if (query.LimitStatus > 0 && query.LimitStatus < delStatus)
            {
                q = q.Where(c => c.LimitStatus == query.LimitStatus);
            }
            //每日执行
            if (query.LimitRepeat > 0 && query.LimitRepeat < delStatus)
            {
                q = q.Where(c => c.LimitRepeat == query.LimitRepeat);
            }
            //收款银行
            if (!string.IsNullOrEmpty(query.WithdrawalBank))
            {
                q = q.Where(c => c.WithdrawalBank.Contains(query.WithdrawalBank));
            }
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyID));
            }
            q = q.Where(c => c.LimitStatus != delStatus);
            #endregion

            int currentPage = query.CurrentPageIndex.Value;
            int pageSize = query.PageSize.Value;

            var list = q.OrderByDescending(r => r.CompanyID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            var count = q.Count();

            return new PagedList<PaymentInterfaceNew>
            {
                TData = list,
                CurrentPageIndex = currentPage,
                TotalCount = count,
                Success = true
            };
        }

        /// <summary>
        /// 获取某第三方接口详细信息
        /// </summary>
        public PaymentInterface GetDetail(PaymentInterfaceQuery s)
        {
            return _context.PaymentInterface.Where(x => x.CompanyID == s.CompanyId && x.PaymentType == s.PaymentType).FirstOrDefault();
        }

        /// <summary>
        /// 添加第三方接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public int AddInterface(PaymentInterfaceQuery request)
        {
            int rows = 0;

            var paymentInterface = new PaymentInterface();

            int companyId = request.CompanyId.Value;

            var existRows = _context.PaymentInterface.Where(e => e.CompanyID == companyId
            && e.PaymentType == request.PaymentType
            && e.LimitStatus != (int)PaymentInterfaceStatus.删除).FirstOrDefault();
            if (existRows != null)
            {
                throw new Exception("同一公司只能新增一笔规则。");
            }

            paymentInterface.CompanyID = companyId;
            //paymentInterface.PaymentType = request.PaymentType;
            paymentInterface.CompanyName = request.CompanyName;

            if (request.permission.CanView)
            {
                paymentInterface.SecretKey = request.SecretKey;
            }

            paymentInterface.PaymentStart = request.PaymentStart;
            paymentInterface.PaymentEnd = request.PaymentEnd;
            paymentInterface.WithdrawalBank = request.WithdrawalBank;
            paymentInterface.DepositType = request.DepositType;
            paymentInterface.PaymentMax = request.PaymentMax;
            if (string.IsNullOrEmpty(request.LimitCloseDate)){
                paymentInterface.LimitCloseDate = null;
            }else{
                paymentInterface.LimitCloseDate = Convert.ToDateTime(request.LimitCloseDate);
            }

            if (string.IsNullOrEmpty(request.LimitOpenDate)){
                paymentInterface.LimitOpenDate = null;
            }else{
                paymentInterface.LimitOpenDate = Convert.ToDateTime(request.LimitOpenDate);
            }

            paymentInterface.LimitRepeat = request.LimitRepeat;
            paymentInterface.LimitStatus = (int)PaymentInterfaceStatus.禁用;
            if (request.PaymentType == (sbyte)PaymentInterfacePaymentType.优凯顺){
                paymentInterface.EnableBalanceCheck = (sbyte)PaymentInterfaceEnableBalanceCheck.启用;
            }
            else {
                paymentInterface.EnableBalanceCheck = (sbyte)PaymentInterfaceEnableBalanceCheck.禁用;
            }
            _context.PaymentInterface.Add(paymentInterface);
            try
            {
                rows = _context.SaveChanges();
            }
            catch (Exception)
            {
                throw new Exception("单一公司只能新增一笔规则。");
            }
            return rows;
        }

        /// <summary>
        /// 修改第三方接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public int EditInterface(PaymentInterfaceQuery s)
        {
            int rows = 0;

            try
            {
                PaymentInterface d = _context.PaymentInterface.Where(x => x.CompanyID == s.CompanyId.Value).FirstOrDefault();
                if (d == null) return -1;

                //d.PaymentType = s.PaymentType;
                d.CompanyName = s.CompanyName;

                if (s.permission.CanView)
                {
                    d.SecretKey = s.SecretKey;
                }

                d.PaymentStart = s.PaymentStart;
                d.PaymentMax = s.PaymentMax;
                d.PaymentEnd = s.PaymentEnd;
                d.WithdrawalBank = s.WithdrawalBank;
                d.DepositType = s.DepositType;
                d.LimitOpenDate = Convert.ToDateTime(s.LimitOpenDate);
                d.LimitCloseDate = Convert.ToDateTime(s.LimitCloseDate);
                d.LimitRepeat = s.LimitRepeat;

                return _context.SaveChanges();
            }
            catch (Exception)
            {
                rows = -3;
            }
            return rows;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="configId"></param>
        /// <returns></returns>
        public int DeleteInterface(PaymentInterfaceQuery s)
        {
            var item = _context.PaymentInterface.Where(x => x.CompanyID == s.CompanyId
            && x.PaymentType == s.PaymentType
            && x.LimitStatus != (int)PaymentInterfaceStatus.删除
            ).FirstOrDefault();
            if (item == null) return -1;
            _context.Remove(item);
            return _context.SaveChanges();
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public int UpdateStatus(PaymentInterfaceQuery request)
        {
            var item = _context.PaymentInterface.Where(x => x.CompanyID == request.CompanyId
            && x.LimitStatus != (int)PaymentInterfaceStatus.删除
            && x.PaymentType == request.PaymentType
            ).FirstOrDefault();
            if (item == null) return -1;
            if (request.Type == 0)
            {
                item.LimitStatus = request.LimitStatus;
            }
            else
            {
                item.LimitRepeat = request.LimitRepeat;
            }
            return _context.SaveChanges();
        }

        #endregion

        /// <summary>
        /// 获取推送地址列表
        /// </summary>
        public PagedList<ExtApiPushUrl> GetPushAddressList(PushAddressQuery query)
        {
            var q = from s in _context.ExtApiPushUrl
                    join c in _context.Company on s.CompanyId equals c.CompanyId
                    select new ExtApiPushUrl
                    {
                        CompanyId = c.CompanyId,
                        Type = s.Type,
                        Url = s.Url,
                        Description = s.Description,
                        SortNo = s.SortNo,
                        Company = c
                    };
            //公司名称
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                q = q.Where(c => c.Company.CompanyName.Contains(query.CompanyName));
            }
            //状态
            if (query.Type > 0)
            {
                q = q.Where(c => c.Type == query.Type);
            }

            int currentPage = query.CurrentPageIndex.Value;
            int pageSize = query.PageSize.Value;
            q = q.OrderByDescending(r => r.Id).Skip((currentPage - 1) * pageSize).Take(pageSize);

            return new PagedList<ExtApiPushUrl>
            {
                TData = q.ToList(),
                CurrentPageIndex = currentPage,
                TotalCount = q.Count(),
                Success = true
            };
        }

        //获取交易类型的值
        public string GetTransType(int companyId, int configValue, string configCode)
        {
            var q = _context.SysConfig.Where(e => e.CompanyId == companyId
            && e.ConfigValue == configValue
            && e.ConfigCode == configCode).FirstOrDefault();
            if (q != null)
            {
                return q.ConfigContent;
            }
            return string.Empty;
        }

        //获取系统配置列表
        public List<SysConfig> GetTransTypeList(SysConfigAddOrEditRequest sysRequest)
        {
            var q = _context.SysConfig.Where(e => e.CompanyId == (int)ReceiptTrans.TranCompanyId
            && e.ConfigValue != 0
            && e.ConfigCode == sysRequest.ConfigCode).ToList();
            return q;
        }

        //获取系统配置列表
        public List<SysConfig> GetTransTypeListNew(SysConfigAddOrEditRequest sysRequest)
        {
            var q = _context.SysConfig.Where(e => e.CompanyId == (int)ReceiptTrans.TranCompanyId
            && e.ConfigCode == sysRequest.ConfigCode).ToList();
            return q;
        }

        //获取公司授权版本号
        public string GetVersion(string code)
        {
            var q = _context.SysConfig.Where(e => e.CompanyId == (int)ReceiptTrans.TranCompanyId
            && e.ConfigCode == code).FirstOrDefault();
            if (q == null) return "2";
            return q.ConfigValue.ToString();
        }

    }
}
